// 普通版
function debounce(func, wait) {
  let timer;

  return function (...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      func.apply(this, args)
    }, wait)
  }
}

// 立即执行版
function debounce(func, wait, immediate) {
  let timer;

  return function (...args) {
    if (timer) clearTimeout(timer)
    if (immediate) {
      // 如果已经执行过，不再执行
      var callNow = !timer;
      timer = setTimeout(() => {
        timer = null;
      }, wait)
      if (callNow) func.apply(this, args)
    } else {
      timer = setTimeout(() => {
        func.apply(this, args)
      }, wait);
    }
  }
}

function debounce(func, wait, immediate) {
  let timer = null

  return function (...args) {
    if (immediate && !timer) {
      func.apply(this, args)
    }
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      func.apply(this, args)
    }, wait)
  }
}